<html>
{% include "head.html" %}
<body class="yui-skin-sam">
  
  {% include "menuHead.html" %}
  <div id="container"></div>
  
  {% include "filterHead.html" %}
  
  <div id="resultats" style="float: left; display:inline;"></div> 
  <div id="grafica" style="float: right; display:inline; width: 700px; height: 500px; margin: 0 auto"></div>
  
  <script type="text/javascript">
  google.load('visualization', '1', {packages:['corechart']});
  YAHOO.util.Event.addListener(window, "load", function() {
        var Event = YAHOO.util.Event,
            Dom = YAHOO.util.Dom;

        initLoadingWindow();
        initSearchFields();
	
        var histColumnDefs = [
            {key:"variable", label: "Variable", sortable: true },
            {key:"dataHora", label:"Data/Hora", sortable:true},
            {label: "Valor",
                    children: [
                              {key:"V0", label: "R", formatter: "formataValor"},
                              {key:"V1", label: "S", formatter: "formataValor"},
                              {key:"V2", label: "T", formatter: "formataValor"},
                              {key:"VU", label: "N/Total", formatter: "formataValor"}
                    ]
            },
            {key:"unitats", label: "Unitat", sortable: false },            
        ];

        YAHOO.widget.DataTable.Formatter.formataValor = function(elCell, oRecord, oColumn, oData)
        {
                  var data = oRecord.getData("valor");
                  if (typeof data == "object")
                  {
                   if (oColumn.field=='V0') 
                       elCell.innerHTML = '<div align="right">'+data[0]+'</div>'; 
                   else if (oColumn.field=='V1')
                       elCell.innerHTML = '<div align="right">'+data[1]+'</div>';
                   else if (oColumn.field=='V2')
                       elCell.innerHTML = '<div align="right">'+data[2]+'</div>';
                   else if (oColumn.field=='VU' && data.length > 3)
                       elCell.innerHTML = '<div align="right"><font style="color: blue;">'+data[3]+'</font></div>';           
                  } else {
                      if (oColumn.field!='V0' && oColumn.field!='V1' && oColumn.field!='V2')
                          elCell.innerHTML = '<div align="right">'+data+'</div>';
                  }
        };
        
        var histDataSource = new YAHOO.util.DataSource("/ws/v2/history/load/");
        histDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        histDataSource.connXhrMode = "queueRequests";
        histDataSource.responseSchema = {
            resultsList: "ResultSet.Lectures",
            fields: ["variable","dataHora","valor","unitats"]
        };

        var histDataTable = new YAHOO.widget.DataTable("resultats", histColumnDefs, histDataSource, 
                                                       {initialLoad: false, scrollable: true, height:"430px", width: "550px"});
                                                            
        histDataTable.subscribe("rowMouseoverEvent", histDataTable.onEventHighlightRow); 
	histDataTable.subscribe("rowMouseoutEvent", histDataTable.onEventUnhighlightRow); 
        histDataTable.subscribe("rowClickEvent", histDataTable.onEventSelectRow);

	function prepareData(data)
	{
	         var titols = [ 'Data/Hora' ], compost = false;
	         if ( typeof data[0].valor == 'object' )
		 {
		       for (var i = 0; i < data[0].valor.length; i++)
		           titols.push(data[0].variable+"."+i);
		       compost = true;
		 } else titols.push(data[0].variable);
		 
	         var listData = [ titols ];
		 for (var i = 0; i < data.length; i++)
		 {
                     dataLine = [data[i].dataHora]
		     if ( compost )
		     {
		          for (var j = 0; j < data[i].valor.length; j++)
		              dataLine.push(data[i].valor[j]);
		     } else dataLine.push(data[i].valor);
		     
	             listData.push(dataLine);
		 }

                 return google.visualization.arrayToDataTable(listData);	  
	}
	
	function drawChart(dataChart)
	{
		 if (dataChart.length==0)
		    return;
		  
	 	 var chart = new google.visualization.LineChart(document.getElementById('grafica'));
	         chart.draw(prepareData(dataChart), { title: 'Grafica de '+dataChart[0].variable, vAxis: { title: dataChart[0].unitats } });
	}
	
        Event.on(Dom.get("search"), "click", function() {   
              var mySuccessHandler = function() {
		  this.onDataReturnInitializeTable.apply(this,arguments);
                  
		  if (Dom.get("chartC").checked && selectVars.value != "ALL")
		     drawChart(arguments[1].results);
		  
                  YAHOO.loading.container.wait.hide();
              };
              
              var myFailureHandler = function() {
                  this.showTableMessage(YAHOO.widget.DataTable.MSG_ERROR, YAHOO.widget.DataTable.CLASS_ERROR);
                  this.onDataReturnAppendRows.apply(this,arguments);
                  YAHOO.loading.container.wait.hide();
              };

              var oCallback = {
                  success : mySuccessHandler,
                  failure : myFailureHandler,
                  scope : histDataTable,
                  argument : histDataTable.getState()
              };
      
              var dataInici = Dom.get("dateFrom").value;
              var dataFi = Dom.get("dateTo").value;
              var node = Dom.get("nodeId").value;
              var analizer = Dom.get("analizerId").value;
              var variable = Dom.get("varC");
	      
              if (dataInici.match("^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4}") && dataFi.match("^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4}"))  
              {
                  YAHOO.loading.container.wait.show();
                  histDataSource.sendRequest(node+"/"+analizer+"/"+selectVars.value+"/"+dataInici+"/"+dataFi, oCallback);   
              } else
                 alert("El format de les dates es incorrecte!");
        });
  });
  </script>   
</body>
</html>

